import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/api/http'
import ports from '@/api/ports'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    current: 0,     // 未登陆值为0，登陆则是会员类型代号
    memberNo: '',
    circleUrl: '',
    name: '',
    coin: '',
    rank: '',
    point: 0,
    search: ''
  },
  mutations: {
    // 改变状态
    TOLOGIN1: (state, login) => {
      state.current = login.type
      state.memberNo = login.status
      console.log(state.current)
    },
    // 注销
    LOGINOUT1: (state) => {
      state.current = 0
      state.memberNo = ''
    },
    EDITMEMBERINFO: (state, info) => {
      state.circleUrl = info.circleUrl
      state.name = info.name
      state.coin = info.coin
      state.rank = info.rank
      state.point = info.point
    },
    EDITEMPLOYEEINFO: (state, info) => {
      state.circleUrl = info.circleUrl
      state.name = info.name
    },
    EDITINFO: (state, info) => {
      state.circleUrl = info.circleUrl
      state.name = info.name
    },
    SEARCH: (state, search) => {
      state.search = search
    }
  },
  //异步方法
  actions: {
    isLogin(context) {
      return new Promise((resolve, reject) => {
        http.get(ports.manage.current,
          res => {
            
            if (res.status === 200) {
              let data = res.data.result.msg
              let memberNo // 登陆编号
              let memberType = data[1]    // 登陆类型
              if (data[1] === '1') {
                // this.username = data[0][0].memberName
                memberNo = data[0][0].memberNo
                let info = {
                  circleUrl: data[0][0].memberIcon,
                  name: data[0][0].memberName,
                  coin: data[0][0].memberCoin,
                  rank: data[0][0].memberRank,
                  point: data[0][0].memberPoint
                }
                console.log('鉴权')
                console.log(info)
                context.commit('EDITMEMBERINFO', info)
              } else if (data[1] === '2') {
                // this.username = data[0][0].employeeName
                memberNo = data[0][0].employeeNo
                let info = {
                  circleUrl: data[0][0].employeeIcon,
                  name: data[0][0].employeeName
                }
                context.commit('EDITEMPLOYEEINFO', info)
              } else if (data[1] === '3') {
                memberNo = data[0][0].administratorNo
                let info = {
                  circleUrl: 'https://i.loli.net/2019/12/06/4LhTjfKoZPBtEv8.png',
                  name: '管理员'
                }
                context.commit('EDITEMPLOYEEINFO', info)
              } else if (data[1] === '4') {
                memberNo = data[0][0].teacherNo
                let info = {
                  circleUrl: data[0][0].teacherIcon,
                  name: data[0][0].teacherName
                }
                context.commit('EDITEMPLOYEEINFO', info)
              }
              let logins = {
                status: memberNo,
                type: memberType
              }
              context.commit('TOLOGIN1', logins)
              resolve()
            } else if (res.status === 401) {
            } else {
              console.log(res)
            }
          })
      })
    }
  }
})
// vue建议在mutation使用大写命名方法
// 只有在mutation中才能改变state，所以在action需要commit一个mutataion



// var video = document.querySelector('video');
// var assetURL = 'frag_bunny.mp4';
// // Need to be specific for Blink regarding codecs
// // ./mp4info frag_bunny.mp4 | grep Codec
// var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
// var totalSegments = 5;
// var segmentLength = 0;
// var segmentDuration = 0;
// var bytesFetched = 0;
// var requestedSegments = [];
// for (var i = 0; i < totalSegments; ++i) requestedSegments[i] = false;
// var mediaSource = null;
// if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
//   mediaSource = new MediaSource;
//   //console.log(mediaSource.readyState); // closed
//   video.src = URL.createObjectURL(mediaSource);
//   mediaSource.addEventListener('sourceopen', sourceOpen);
// } else {
//   console.error('Unsupported MIME type or codec: ', mimeCodec);
// }
// var sourceBuffer = null;
// function sourceOpen(_) {
//   sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
//   getFileLength(assetURL, function (fileLength) {
//     console.log((fileLength / 1024 / 1024).toFixed(2), 'MB');
//     //totalLength = fileLength;
//     segmentLength = Math.round(fileLength / totalSegments);
//     //console.log(totalLength, segmentLength);
//     fetchRange(assetURL, 0, segmentLength, appendSegment);
//     requestedSegments[0] = true;
//     video.addEventListener('timeupdate', checkBuffer);
//     video.addEventListener('canplay', function () {
//       segmentDuration = video.duration / totalSegments;
//       video.play();
//     });
//     video.addEventListener('seeking', seek);
//   });
// };
// function getFileLength(url, cb) {
//   var xhr = new XMLHttpRequest;
//   xhr.open('head', url);
//   xhr.onload = function () {
//     cb(xhr.getResponseHeader('content-length'));
//   };
//   xhr.send();
// };
// function fetchRange(url, start, end, cb) {
//   var xhr = new XMLHttpRequest;
//   xhr.open('get', url);
//   xhr.responseType = 'arraybuffer';
//   xhr.setRequestHeader('Range', 'bytes=' + start + '-' + end);
//   xhr.onload = function () {
//     console.log('fetched bytes: ', start, end);
//     bytesFetched += end - start + 1;
//     cb(xhr.response);
//   };
//   xhr.send();
// };
// function appendSegment(chunk) {
//   sourceBuffer.appendBuffer(chunk);
// };
// function checkBuffer(_) {
//   var currentSegment = getCurrentSegment();
//   if (currentSegment === totalSegments && haveAllSegments()) {
//     console.log('last segment', mediaSource.readyState);
//     mediaSource.endOfStream();
//     video.removeEventListener('timeupdate', checkBuffer);
//   } else if (shouldFetchNextSegment(currentSegment)) {
//     requestedSegments[currentSegment] = true;
//     console.log('time to fetch next chunk', video.currentTime);
//     fetchRange(assetURL, bytesFetched, bytesFetched + segmentLength, appendSegment);
//   }
//   //console.log(video.currentTime, currentSegment, segmentDuration);
// };
// function seek(e) {
//   console.log(e);
//   if (mediaSource.readyState === 'open') {
//     sourceBuffer.abort();
//     console.log(mediaSource.readyState);
//   } else {
//     console.log('seek but not open?');
//     console.log(mediaSource.readyState);
//   }
// };
// function getCurrentSegment() {
//   return ((video.currentTime / segmentDuration) | 0) + 1;
// };
// function haveAllSegments() {
//   return requestedSegments.every(function (val) { return !!val; });
// };
// function shouldFetchNextSegment(currentSegment) {
//   return video.currentTime > segmentDuration * currentSegment * 0.8 &&
//     !requestedSegments[currentSegment];
// };
